package com.kx.yooli.kx.wechat.utils.date;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class DateCustomUtils {
    private static final Log log = LogFactory.getLog(DateCustomUtils.class);
    public static final String defaultDateFormat = "yyyy-MM-dd HH:mm:ss";
    public static final String defaultDayFormat = "yyyy-MM-dd";
    public static final String defaultDayFormats = "yyyyMMdd";
    private static final String[] weeks = new String[]{"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"};

    public DateCustomUtils() {
    }

    public static void copyYearMonthDay(Calendar calendar, Calendar calendar1) {
        calendar.set(1, calendar1.get(1));
        calendar.set(2, calendar1.get(2));
        calendar.set(5, calendar1.get(5));
    }

    public static String formatEnDate(Date date) {
        SimpleDateFormat simpledateformat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");
        return simpledateformat.format(date).replaceAll("上午", "AM").replaceAll("下午", "PM");
    }

    public static Date getStartOfTarDay(Date date) {
        Calendar todayStart = Calendar.getInstance();
        todayStart.setTime(date);
        todayStart.set(11, 0);
        todayStart.set(12, 0);
        todayStart.set(13, 0);
        todayStart.set(14, 0);
        return todayStart.getTime();
    }

    public static Date getEndOfTarDay(Date date) {
        Calendar todayEnd = Calendar.getInstance();
        todayEnd.setTime(date);
        todayEnd.set(11, 23);
        todayEnd.set(12, 59);
        todayEnd.set(13, 59);
        todayEnd.set(14, 999);
        return todayEnd.getTime();
    }

    public static String getFormatedDate(Date date) {
        return getFormatedDate(date, "yyyy-MM-dd HH:mm:ss");
    }

    public static String getFormatedDate(Date now, String format) {
        try {
            DateFormat df = format == null ? new SimpleDateFormat() : new SimpleDateFormat(format);
            String str = now == null ? null : df.format(now);
            return str;
        } catch (Exception var4) {
            log.error("无法解析 format: " + format, var4);
            return null;
        }
    }

    public static String getSimplesFormatDate(Date date) {
        return getFormatedDate(date, "yyyyMMdd");
    }

    public static String getSimpleFormatDate(Date date) {
        return getFormatedDate(date, "yyyy-MM-dd");
    }

    public static String getSimpleFormatedDateNow() {
        return getSimpleFormatDate(new Date());
    }

    public static String getStandTime() {
        return getFormatedDate(new Date());
    }

    public static int getWeekByDate(Date date) {
        int a = 0;
        GregorianCalendar cal = new GregorianCalendar();

        try {
            cal.setTime(date);
            a = cal.get(7);
        } catch (Exception var4) {
            log.error("通过Date得到week发生异常", var4);
        }

        return a;
    }

    public static Date parseDate(String s) {
        Date date = null;

        try {
            date = parseDate(s, new String[]{"yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd"});
        } catch (Exception var3) {
            log.warn("Pase the Date(" + s + ") occur errors:" + var3.getMessage());
        }

        return date;
    }

    public static Date parseDate(String str, String[] parsePatterns) throws ParseException {
        return  DateUtils.parseDate(str, parsePatterns);
    }

    public static Date parseStringToDate(String date) {
        return parseStringToDate(date, "yyyy-MM-dd");
    }

    public static Date parseStringToDate(String date, String format) {
        DateFormat df = new SimpleDateFormat(format);
        Date nowDate = null;

        try {
            nowDate = df.parse(date);
        } catch (ParseException var5) {
            log.error("无法解析" + date, var5);
        }

        return nowDate;
    }

    public static Calendar setEndDay(Calendar calendar) {
        calendar.set(11, 23);
        calendar.set(12, 59);
        calendar.set(13, 59);
        return calendar;
    }

    public static Calendar setStartDay(Calendar calendar) {
        calendar.set(11, 0);
        calendar.set(12, 0);
        calendar.set(13, 0);
        return calendar;
    }

    public static Date convertString(String value, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        if (value == null) {
            return null;
        } else {
            try {
                return sdf.parse(value);
            } catch (Exception var4) {
                return null;
            }
        }
    }

    public static Date convertString(String value) {
        return convertString(value, "yyyy-MM-dd HH:mm:ss");
    }

    public static Date convertDateString(String value) {
        return convertString(value, "yyyy-MM-dd");
    }

    public static String getFormattedString(XMLGregorianCalendar xmlDate, String datePattern) {
        SimpleDateFormat sd = new SimpleDateFormat(datePattern);
        Calendar calendar = xmlDate.toGregorianCalendar();
        return sd.format(calendar.getTime());
    }

    public static XMLGregorianCalendar convert2XMLCalendar(Calendar calendar) {
        try {
            DatatypeFactory dtf = DatatypeFactory.newInstance();
            return dtf.newXMLGregorianCalendar(calendar.get(1), calendar.get(2) + 1, calendar.get(5), calendar.get(10), calendar.get(12), calendar.get(13), calendar.get(14), calendar.get(15) / '\uea60');
        } catch (DatatypeConfigurationException var2) {
            log.error("", var2);
            return null;
        }
    }

    public static XMLGregorianCalendar convert2XMLCalendar(Date date) {
        GregorianCalendar cal = new GregorianCalendar();
        cal.setTime(date);
        XMLGregorianCalendar gc = null;

        try {
            gc = DatatypeFactory.newInstance().newXMLGregorianCalendar(cal);
        } catch (Exception var4) {
            log.error("", var4);
        }

        return gc;
    }

    public static int daysOfTwo(Date fDate, Date oDate) {
        Calendar fCalendar = Calendar.getInstance();
        Calendar oCalendar = Calendar.getInstance();
        fCalendar.setTime(fDate);
        oCalendar.setTime(oDate);
        fCalendar.set(11, 0);
        fCalendar.set(12, 0);
        fCalendar.set(13, 0);
        oCalendar.set(11, 0);
        oCalendar.set(12, 0);
        oCalendar.set(13, 0);
        int days = ((int)(oCalendar.getTime().getTime() / 1000L) - (int)(fCalendar.getTime().getTime() / 1000L)) / 3600 / 24;
        return days;
    }

    public static int monthOfTwo(Date fDate, Date oDate) {
        Calendar fCalendar = Calendar.getInstance();
        Calendar oCalendar = Calendar.getInstance();
        fCalendar.setTime(fDate);
        oCalendar.setTime(oDate);
        fCalendar.set(11, 0);
        fCalendar.set(12, 0);
        fCalendar.set(13, 0);
        oCalendar.set(11, 0);
        oCalendar.set(12, 0);
        oCalendar.set(13, 0);
        int months = oCalendar.get(2) - fCalendar.get(2);
        return months;
    }

    public static Date getBeforeDay(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(5, -1);
        date = calendar.getTime();
        return date;
    }

    public static String getDay(String day) {
        String[] aryDay = day.split(",");
        int len = aryDay.length;
        String str = "";

        for(int i = 0; i < len; ++i) {
            String tmp = aryDay[i];
            tmp = tmp.equals("L") ? "最后一天" : tmp;
            if (i < len - 1) {
                str = str + tmp + ",";
            } else {
                str = str + tmp;
            }
        }

        return str;
    }

    public static XMLGregorianCalendar translateReserveTime(Date date) {
        GregorianCalendar gcal = new GregorianCalendar();
        XMLGregorianCalendar xgcal = null;

        try {
            xgcal = DatatypeFactory.newInstance().newXMLGregorianCalendar(gcal);
        } catch (DatatypeConfigurationException var5) {
            log.error("", var5);
        }

        gcal.setTime(date);

        try {
            xgcal = DatatypeFactory.newInstance().newXMLGregorianCalendar(gcal);
        } catch (DatatypeConfigurationException var4) {
            log.error("", var4);
        }

        return xgcal;
    }

    public static java.sql.Date date2date(Date date) {
        if (null == date) {
            date = new Date();
        }

        java.sql.Date sd = new java.sql.Date(date.getTime());
        return sd;
    }

    public static Date timestamp2date(Timestamp timestamp) {
        Date date = null;

        try {
            date = timestamp;
        } catch (Exception var3) {
            date = null;
        }

        return date;
    }

    public static String timestamp2Str(Timestamp timestamp) {
        return getSimpleFormatDate(timestamp2date(timestamp));
    }

    public static Timestamp date2timestamp(Date date) {
        Timestamp t = new Timestamp(date.getTime());
        return t;
    }

    public static Date dateAddSub(Date date, int a, int b) {
        GregorianCalendar gc = new GregorianCalendar();
        gc.setTime(date);
        gc.add(a, b);
        gc.getTime();
        return gc.getTime();
    }

    public static boolean compareHMS(String target, String reserveTime) {
        boolean flag = true;

        try {
            Date reserveTimeD = convertString(reserveTime, "HH:mm:ss");
            Date targetD = convertString(target, "HH:mm:ss");
            Calendar reserveTimeCal = Calendar.getInstance();
            reserveTimeCal.setTime(reserveTimeD);
            int reserveTimeHour = reserveTimeCal.get(11);
            int reserveTimeMinute = reserveTimeCal.get(12);
            int reserveTimeSecond = reserveTimeCal.get(13);
            Calendar targetCal = Calendar.getInstance();
            targetCal.setTime(targetD);
            int targetHour = targetCal.get(11);
            int targetMinute = targetCal.get(12);
            int targetSecond = targetCal.get(13);
            if (reserveTimeHour > targetHour) {
                flag = false;
                return flag;
            } else if (reserveTimeHour == targetHour && reserveTimeMinute > targetMinute) {
                flag = false;
                return flag;
            } else if (reserveTimeHour == targetHour && reserveTimeMinute == targetMinute && reserveTimeSecond > targetSecond) {
                flag = false;
                return flag;
            } else if (0 == reserveTimeHour) {
                flag = true;
                return flag;
            } else {
                return flag;
            }
        } catch (Exception var13) {
            flag = false;
            return flag;
        }
    }

    public static Date datetimesToDate(Date date) {
        if (null == date) {
            date = new Date();
        }

        try {
            return parseStringToDate(getFormatedDate(date, "yyyy-MM-dd"));
        } catch (Exception var2) {
            log.error("转换错误" + date, var2);
            return parseStringToDate(getFormatedDate(new Date(), "yyyy-MM-dd"));
        }
    }

    public static String getCNDateNow() {
        return formatDateCn(Calendar.getInstance());
    }

    public static String getCNDate(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        return formatDateCn(cal);
    }

    private static String formatDateCn(Calendar cal) {
        try {
            StringBuffer str = new StringBuffer();
            str.append(cal.get(1)).append("年");
            str.append(cal.get(2) + 1).append("月");
            str.append(cal.get(5)).append("日");
            str.append(getWeek(cal.get(7)));
            return str.toString();
        } catch (Exception var2) {
            log.error("得到默认中文日期格式发生异常", var2);
            return null;
        }
    }

    public static String getWeek(int week) {
        if (week > 0 && week <= 7) {
            return weeks[week - 1];
        } else {
            throw new IllegalArgumentException("week must be number 1-7![your week is " + week + "]");
        }
    }

    public static String getSysOracleDate() {
        StringBuffer sb = new StringBuffer();
        String[] strs = (new Date()).toString().split(" ");
        sb.append(strs[2] + "-");
        sb.append(strs[1] + "-");
        sb.append(strs[5]);
        return sb.toString();
    }

    public static boolean isSameDay(Date time1, Date time2) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(time1);
        int year = cal.get(1);
        int month = cal.get(2);
        int day = cal.get(5);
        cal.setTime(time2);
        if (year != cal.get(1)) {
            return false;
        } else if (month != cal.get(2)) {
            return false;
        } else {
            return day == cal.get(5);
        }
    }

    public static boolean isToday(Date time) {
        return isSameDay(new Date(), time);
    }

    public static Date getPreMonthLastDay(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(5, 0);
        return cal.getTime();
    }

    public static boolean between(Date date, Date start, Date end) {
        return date.compareTo(end) <= 0 && date.compareTo(start) > 0;
    }

    public static String getStringdate(String date) {
        String[] datestr = date.split("-");
        StringBuffer sb = new StringBuffer();

        for(int i = 0; i < datestr.length; ++i) {
            sb.append(datestr[i]);
        }

        return sb.toString();
    }

    public static Date strToDate(String strDate) {
        String jdkDateFormat = "yyyy-MM-dd";
        SimpleDateFormat dateFormat = new SimpleDateFormat(jdkDateFormat);
        Date date = null;

        try {
            date = dateFormat.parse(strDate);
        } catch (ParseException var5) {
            System.out.println(var5.getMessage());
        }

        return date;
    }

    public static String dateToString(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        String time = format.format(date);
        return time;
    }

    public static String getBeforeDate() {
        Date date = getBeforeDay(new Date());
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String beforedate = format.format(date);
        return beforedate;
    }

    public static String getBeforeDate(String date, String flag) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(strToDate(date));
        if ("sub".equals(flag)) {
            calendar.add(2, -1);
        } else if ("add".equals(flag)) {
            calendar.add(2, 1);
        }

        return simpleDateFormat.format(calendar.getTime());
    }

    public static String getMonth(Calendar calendar) {
        String strMonth = "";
        int month = calendar.get(2) + 1;
        if (month < 10) {
            strMonth = "0" + month;
        } else {
            strMonth = String.valueOf(month);
        }

        return strMonth;
    }

    public static Date addDays(Date date, int amount) {
        return add(date, 5, amount);
    }

    public static Date addMonths(Date date, int amount) {
        return add(date, 2, amount);
    }

    public static Date addWeeks(Date date, int amount) {
        return add(date, 3, amount);
    }

    public static Date addYears(Date date, int amount) {
        return add(date, 1, amount);
    }

    public static Date add(Date date, int calendarField, int amount) {
        if (date == null) {
            throw new IllegalArgumentException("The date must not be null");
        } else {
            Calendar c = Calendar.getInstance();
            c.setTime(date);
            c.add(calendarField, amount);
            return c.getTime();
        }
    }

    public static String getWorkBeginDate(String workSpan) {
        if (StringUtils.isNotEmpty(workSpan) && StringUtils.isNumeric(workSpan)) {
            Integer workTimeSpan = Integer.valueOf(workSpan);
            Calendar calendar = Calendar.getInstance();
            if (workTimeSpan > 999) {
                workTimeSpan = 12;
            }

            calendar.add(2, -workTimeSpan);
            Integer year = calendar.get(1);
            Integer month = calendar.get(2) + 1;
            Integer day = calendar.get(5);
            return year + "-" + month + "-" + day;
        } else {
            return null;
        }
    }

    public static String getBirthdayByCertNo(String certNo) {
        if (StringUtils.isNotEmpty(certNo)) {
            String birthYear = certNo.substring(6, 10);
            String birthMonth = certNo.substring(10, 12);
            String birthDay = certNo.substring(12, 14);
            return birthYear + "-" + birthMonth + "-" + birthDay;
        } else {
            return null;
        }
    }

    public static Date getDateOfBirthFromCertNo(String certNo) {
        if (certNo != null && certNo.length() == 18) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            String year = certNo.substring(6, 10);
            String month = certNo.substring(10, 12);
            String day = certNo.substring(12, 14);
            String date1 = year + "-" + month + "-" + day;

            try {
                Date date = format.parse(date1);
                return date;
            } catch (ParseException var8) {
                var8.printStackTrace();
                return null;
            }
        } else {
            return null;
        }
    }

    public static int getAge(String certNo) {
        Date birthDay = getDateOfBirthFromCertNo(certNo);
        if (birthDay == null) {
            return 0;
        } else {
            Calendar cal = Calendar.getInstance();
            if (cal.before(birthDay)) {
                return 0;
            } else {
                int yearNow = cal.get(1);
                int monthNow = cal.get(2);
                int dayOfMonthNow = cal.get(5);
                cal.setTime(birthDay);
                int yearBirth = cal.get(1);
                int monthBirth = cal.get(2);
                int dayOfMonthBirth = cal.get(5);
                int age = yearNow - yearBirth;
                if (monthNow <= monthBirth) {
                    if (monthNow == monthBirth) {
                        if (dayOfMonthNow < dayOfMonthBirth) {
                            --age;
                        }
                    } else {
                        --age;
                    }
                }

                return age;
            }
        }
    }

    public static int compareOfTwoDays(Date startDate, Date endDate) {
        Calendar startCalendar = Calendar.getInstance();
        Calendar endCalendar = Calendar.getInstance();
        startCalendar.setTime(startDate);
        endCalendar.setTime(endDate);
        int compare = (int)startCalendar.getTime().getTime() - (int)endCalendar.getTime().getTime();
        return compare;
    }

    public static boolean isSameMonth(Date date1, Date date2) {
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date1);
        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(date2);
        boolean isSameYear = cal1.get(1) == cal2.get(1);
        boolean isSameMonth = isSameYear && cal1.get(2) == cal2.get(2);
        return isSameMonth;
    }

    public static Date getRandomOfTarDay(Date date, int hour, int minute, int second) {
        Calendar todayStart = Calendar.getInstance();
        todayStart.setTime(date);
        todayStart.set(11, hour);
        todayStart.set(12, minute);
        todayStart.set(13, second);
        todayStart.set(14, 0);
        return todayStart.getTime();
    }
}
